package crm8000.Controllers

import crm8000.Models.User;
import crm8000.services.PermissionService
import crm8000.services.UserService
import grails.converters.JSON

class UserController {

	static allowedMethods = [loginPOST: 'POST', changeMyPasswordPOST: 'POST', users: 'POST',
		changePassword: 'POST', orgParentName: 'POST', editOrg: 'POST', deleteOrg: 'POST',
		editUser: 'POST', deleteUser: 'POST', queryData: 'POST']

	UserService userService

	PermissionService permissionService

	def login() {
		if (userService.loginUserId) {
			redirect(uri: "/")
		}
	}

	def loginPOST() {
		def result = userService.doLogin(params.loginName, params.password)

		render result as JSON
	}

	def changeMyPassword() {
		def user = User.findById(userService.loginUserId)

		[loginUserId: user.id, loginUserName: user.name, loginName: user.loginName]
	}

	def changeMyPasswordPOST() {
		def result = userService.changeMyPassword(params.userId, params.oldPassword, params.newPassword)

		render result as JSON
	}

	def changePassword() {
		def result = userService.changePassword(params.id, params.password)

		render result as JSON
	}

	def index() {
		if (!permissionService.hasPermission("-8999")) {
			redirect controller: "home"
		}

		[loginUserName: userService.loginUserName]
	}

	def allOrgs() {
		def result = userService.allOrgs()

		// 组织结构目前最大只允许3级
		render(contentType: "application/json") {
			array {
				for (org1 in result) {
					node1 id: org1.id, text: org1.name, fullName: org1.fullName, orgCode: org1.orgCode, leaf: org1.leaf,
					expanded: true,
					children: array {
						for (org2 in org1.children) {
							node2 id: org2.id, text: org2.name, fullName: org2.fullName, orgCode: org2.orgCode, leaf: org2.leaf,
							children: array {
								for (org3 in org2.children) {
									node3 id: org3.id, text: org3.name, fullName: org3.fullName, orgCode: org3.orgCode, leaf: org3.leaf,
									children: array {}
								}
							}
						}
					}
				}
			}
		}
	}

	def users() {
		def result = userService.allUsers(params.orgId)

		render result as JSON
	}

	def orgParentName() {
		def org = userService.orgInfo(params.id)

		render(contentType: "application/json") { parentOrgName = org.parentOrgName  }
	}

	def editOrg() {
		def result = userService.editOrg(params)

		render result as JSON
	}

	def deleteOrg() {
		def result = userService.deleteOrg(params.id)

		render result as JSON
	}

	def editUser() {
		def result = userService.editUser(params)

		render result as JSON
	}

	def deleteUser() {
		def result = userService.deleteUser(params.id)

		render result as JSON
	}

	def queryData() {
		def data = userService.queryData(params.queryKey)

		render(contentType: "application/json") {
			array {
				for (item in data) {
					user id: item.id, loginName: item.loginName, name: item.name
				}
			} }
	}
}